package vboot.core.common.utils.lang;

import vboot.core.common.mvc.pojo.Ztree;

import java.util.ArrayList;
import java.util.List;

public class TreeUtils {

    //高性能转换，但是要求顶层有pid,这里假设为0
//    public static List<Ztree> buildTree(List<Ztree> pidList) {
//        Map<String, List<Ztree>> pidListMap = pidList.stream().collect(Collectors.groupingBy(Ztree::getPid));
//        pidList.stream().forEach(item -> item.setChildren(pidListMap.get(item.getId())));
//        //返回结果也改为返回顶层节点的list
//        return pidListMap.get("0");
//    }

    public static List<Ztree> build(List<Ztree> nodes) {
        List<Ztree> list = new ArrayList<>();
        for (Ztree node : nodes) {
            if (node.getPid() == null) {
                list.add(findZtreeChildrenByTier(node, nodes));
            } else {
                boolean flag = false;
                for (Ztree node2 : nodes) {
                    if (node.getPid().equals(node2.getId())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    list.add(findZtreeChildrenByTier(node, nodes));
                }
            }
        }
        return list;
    }

    //递归查找子节点
    private static Ztree findZtreeChildrenByTier(Ztree node, List<Ztree> nodes) {
        for (Ztree item : nodes) {
            if (node.getId().equals(item.getPid())) {
                if (node.getChildren() == null) {
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(findZtreeChildrenByTier(item, nodes));
            }
        }
        return node;
    }

    public static <T extends Ztree> List<T> buildEtree(List<T> nodes) {
        List<T> list = new ArrayList<>();
        for (T node : nodes) {
            if (node.getPid() == null) {
                list.add(findEtreeChildrenByTier(node, nodes));
            } else {
                boolean flag = false;
                for (T node2 : nodes) {
                    if (node.getPid().equals(node2.getId())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    list.add(findEtreeChildrenByTier(node, nodes));
                }
            }
        }
        return list;
    }

    private static <T extends Ztree> T findEtreeChildrenByTier(T node, List<T> nodes) {
        for (T item : nodes) {
            if (node.getId().equals(item.getPid())) {
                if (node.getChildren() == null) {
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(findEtreeChildrenByTier(item, nodes));
            }
        }
        return node;
    }

}
